package cn.ecut.servlet;

import cn.ecut.model.News;
import cn.ecut.model.User;
import cn.ecut.services.Newsservices;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("news_publish")
public class NewsPublishServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String context=req.getParameter("context");
        String sort=req.getParameter("sort");
        String title=req.getParameter("title");
        String subtitle=req.getParameter("subtitle");
        Object o=req.getSession().getAttribute("user");
        User user=new User();
        String msg="";
        if(o instanceof User){
            user=(User) o;
        }
        else{
            msg="没有登陆。";
            req.setAttribute("msg",msg);
            req.getRequestDispatcher("false.jsp").forward(req,resp);
        }

        News news=new News();
        news.setUserid(user.getId());
        news.setContext(context);
        news.setSort(sort);
        news.setUsername(user.getUsername());
        news.setTitle(title);
        news.setSubtitle(subtitle);
        Newsservices newsservices=new Newsservices();
        if(newsservices.AddNews(news)){
            msg="发布成功。";
            req.setAttribute("msg",msg);
            req.getRequestDispatcher("success.jsp").forward(req,resp);
        }else{
            msg="发布失败。";
            req.setAttribute("msg",msg);
            req.getRequestDispatcher("publish.jsp").forward(req,resp);
        }
    }
}
